package com.bawei.park2211a.news

import androidx.paging.PagingData
import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.bawei.base.bean.NewsEntity
import com.bawei.base.net.ApiService

class NewsDataSource(var apiService: ApiService) : PagingSource<Int, NewsEntity>() {
    override fun getRefreshKey(state: PagingState<Int, NewsEntity>): Int? {
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, NewsEntity> {
       return try {
            val page = params.key ?: 1
            val newsList = apiService.newsList()
            var nextPage = if (newsList.data.isNotEmpty()) page + 1 else null
            LoadResult.Page(newsList.data, null, nextPage)
        } catch (e: Exception) {
            LoadResult.Error(e)
        }

    }
}